#include "MCEllipseParametricWindow.h"
#include "ui_MCEllipseParametricWindow.h"
#include <qvalidator.h>

MCEllipseParametricWindow::MCEllipseParametricWindow(MCCommand *command, MCEllipseVisual *ellipseVisual, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MCEllipseParametricWindow),
    _currentCommand(command),
    _ellipseVisual(ellipseVisual),
    _ellipse(ellipseVisual->ellipse())
{
    ui->setupUi(this);

    ui->x1_le->setText(QString::number(_ellipse.center().x));
    ui->y1_le->setText(QString::number(_ellipse.center().y));
    ui->radius_le->setText(QString::number(_ellipse.rx()));
    ui->radiusy_le->setText(QString::number(_ellipse.ry()));
}

MCEllipseParametricWindow::~MCEllipseParametricWindow()
{
    delete ui;
}

void MCEllipseParametricWindow::on_x1_le_textChanged(const QString &arg1)
{
    if (isTextValid(arg1))
    {
        double x = arg1.toDouble();
        _ellipse = MCEllipse2D(MCPoint2D(x, _ellipse.center().y), _ellipse.rx(), _ellipse.ry());
    }

    updateValue();
}


void MCEllipseParametricWindow::on_y1_le_textChanged(const QString &arg1)
{
    if (isTextValid(arg1))
    {
        double y = arg1.toDouble();
        _ellipse = MCEllipse2D(MCPoint2D(_ellipse.center().x, y), _ellipse.rx(), _ellipse.ry());
    }

    updateValue();
}


void MCEllipseParametricWindow::on_radius_le_textChanged(const QString &arg1)
{
    if (isTextValid(arg1))
    {
        double rx = arg1.toDouble();
        _ellipse = MCEllipse2D(_ellipse.center(), rx, _ellipse.ry());
    }

    updateValue();
}


void MCEllipseParametricWindow::on_radiusy_le_textChanged(const QString &arg1)
{
    if (isTextValid(arg1))
    {
        double ry = arg1.toDouble();
        _ellipse = MCEllipse2D(_ellipse.center(), _ellipse.rx(), ry);
    }

    updateValue();
}


void MCEllipseParametricWindow::on_apply_b_clicked()
{
    this->close();
    _currentCommand->finalize();
}


void MCEllipseParametricWindow::on_terminate_b_clicked()
{
    this->close();
    _currentCommand->terminate();
}

bool MCEllipseParametricWindow::isTextValid(QString text)
{
    QDoubleValidator validator;
    int pos = 0;
    QValidator::State state = validator.validate(text, pos);

    if (state == QValidator::Acceptable)
    {
        return true;
    }

    return false;
}

void MCEllipseParametricWindow::updateValue()
{
    _ellipseVisual->update(_ellipse);
    _currentCommand->presenter_()->redraw();
}

